/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "tim.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "Queue.h"
#include "oled.h"
#include <stdio.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
CircularQueue g_queue;             //队列结构体
uint16_t g_current_angle = 0;      //队列当前角度
uint8_t g_next_value = 1;          //下一个值            
char message1[20] = "";            //调试值1
char message2[20] = "";            //调试值2
uint8_t highlightCount = 0;        //高亮计数
uint8_t g_animation_timer = 0;     // 动画定时器
uint8_t g_display_items[9] = {0};  // 显示项数组
uint8_t g_display_count = 0;       // 当前显示项数量
uint8_t g_queue_status = 0;        // 队列状态 (0:正常, 1:满, 2:空)
bool g_add_mode = true;            // 添加模式标志 (true:添加, false:移除)
OperationMode current_mode = MODE_ADD;

typedef struct {
  uint8_t startSector;
  Highlightmode mode;
  uint8_t number;
}HighlightSetting;

typedef struct {
  uint8_t sector; // 当前扇区
  uint8_t value;  // 显示的值
} DisplayItem;


// typedef struct {
//   uint8_t type;      // 高亮类型
//   uint8_t startSector;
//   uint8_t endSector;
// } HighlightSetting;

HighlightSetting highlightSettings[Queue_Capacity];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void Update_LED_Status(void){
  // 根据队列状态更新LED
  if (Queue_isFull(&g_queue)) {
    HAL_GPIO_WritePin(LED_RED_GPIO_Port, LED_RED_Pin, GPIO_PIN_SET);
    g_queue_status = 1; // 队列满
    g_add_mode = false;
  } else if (Queue_isEmpty(&g_queue)) {
    HAL_GPIO_WritePin(LED_RED_GPIO_Port, LED_RED_Pin, GPIO_PIN_SET);
    g_queue_status = 2; // 队列空
    g_add_mode = true;
    g_next_value = 1;
  } else {
    HAL_GPIO_WritePin(LED_RED_GPIO_Port, LED_RED_Pin, GPIO_PIN_RESET);
    g_queue_status = 0; // 队列正常
  }
}
//定时器中断回调
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
  if(htim == &htim3){
    /*测试代码*/
    // sprintf(message,"counter : %d",counter);
    // OLED_NewFrame();
    // OLED_PrintString(1,1,message,&font16x16,OLED_COLOR_NORMAL);
    // OLED_ShowFrame();
  //   if(!Queue_isEmpty(&g_queue)){
  //     OLED_NewFrame();

  //     //绘制基线
  //     OLED_DrawCircle(CircleCenterX,CircleCenterY,CircleRadius,OLED_COLOR_NORMAL); 
  //     OLED_DrawCross();

  // for (uint8_t i = 0; i < highlightCount; i++) {
  //       highlightSettings[i].startSector = (highlightSettings[i].startSector + 1) % 9;
  //           sprintf(message1,"sS:");
  //           OLED_PrintString(80,1,message1,&font16x16,OLED_COLOR_NORMAL);
  //           sprintf(message2,"%d",highlightSettings[i].startSector);
  //           OLED_PrintString(80,16,message2,&font16x16,OLED_COLOR_NORMAL);


  //       OLED_DrawNumberInSector(highlightSettings[i].startSector, highlightSettings[i].number);
  //     }      //显示队列状态模块
  //     // sprintf(message, "status:%d/%d", g_queue.count, Queue_Capacity);
  //     // OLED_PrintString(0, 0, message, &font16x16, OLED_COLOR_NORMAL);

      
      // 更新旋转角度
      g_current_angle = (g_current_angle + ROTATION_SPEED) % 360;
      
      // 绘制新帧
      OLED_NewFrame();
      
      // 绘制圆形背景
      OLED_DrawCircle(CircleCenterX, CircleCenterY, CircleRadius, OLED_COLOR_NORMAL);
      OLED_DrawCross(); // 绘制交叉线
      
      // 绘制数字
      for (uint8_t i = 0; i < g_display_count; i++) {
        uint16_t sector_angle = g_current_angle + (i * 40); // 每个扇区40度
        uint8_t x = CircleCenterX + (CircleRadius / 1.25) * cos((sector_angle + 20) * M_PI / 180);
        uint8_t y = CircleCenterY + (CircleRadius / 1.25) * sin((sector_angle + 20) * M_PI / 180);
        
        // 显示数字
        char num_str[2];
        num_str[0] = '0' + g_display_items[i];
        num_str[1] = '\0';
        OLED_PrintString(x, y, num_str, &font16x16, OLED_COLOR_NORMAL);
      }
      
      // 显示队列状态
      char status_msg[20];
      if (g_queue_status == 1) {
        sprintf(status_msg, "Q: Full");
      } else if (g_queue_status == 2) {
        sprintf(status_msg, "Q: Empty");
      } else {
        sprintf(status_msg, "Q: %d/%d", g_queue.count, Queue_Capacity);
      }
      OLED_PrintString(64, 48, status_msg, &font16x16, OLED_COLOR_NORMAL);

      OLED_ShowOperationMode(current_mode);
      
      OLED_ShowFrame();

      

      Update_LED_Status();
    }
  }

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin){
  //消抖
  static uint32_t last_tick = 0;
  if(HAL_GetTick() - last_tick < 50) return;
  last_tick = HAL_GetTick();

  if(GPIO_Pin == Key1_Pin){
    //测试代码
    // HAL_GPIO_TogglePin(LED_RED_GPIO_Port,LED_RED_Pin);

  if (g_add_mode) {
      // 添加模式
      if (Queue_EnQueue(&g_queue, g_next_value)) {
        // 更新显示项
        if (g_display_count < Queue_Capacity) {
          g_display_items[g_display_count++] = g_next_value;
        }
        g_next_value = (g_next_value % 9) + 1; // 循环1-9
      }
    } else {
      // 移除模式
      uint8_t removed_val;
      if (Queue_DeQueue(&g_queue, &removed_val)) {
        // 更新显示项
        for (uint8_t i = 0; i < g_display_count; i++) {
          if (g_display_items[i] == removed_val) {
            // 移动显示项数组
            for (uint8_t j = i; j < g_display_count - 1; j++) {
              g_display_items[j] = g_display_items[j + 1];
            }
            g_display_count--;
            break;
          }
        }
      }
    }    
    current_mode = g_add_mode ? MODE_ADD : MODE_REMOVE;
    Update_LED_Status();
    
  }
  // else if(GPIO_Pin == Key2_Pin){
  //    HAL_GPIO_TogglePin(LED_RED_GPIO_Port,LED_RED_Pin);
  // }
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_TIM3_Init();
  /* USER CODE BEGIN 2 */
  HAL_Delay(50);
  OLED_Init();
  Queue_Init(&g_queue);
  HAL_TIM_Base_Start_IT(&htim3);

  //初始界面绘制
  OLED_NewFrame();
  OLED_DrawCircle(CircleCenterX,CircleCenterY,CircleRadius,OLED_COLOR_NORMAL);
  OLED_DrawCross();    
  OLED_ShowFrame();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    __WFI();
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
